/**
 * 智能体管理模块
 * 支持添加、删除、更新智能体，并持久化到 localStorage
 */

export interface Agent {
  id: string;
  name: string;
  url: string;
  description?: string;
  icon?: string;
  createdAt: string;
  updatedAt: string;
}

const STORAGE_KEY = 'feng-admin-agents';

/**
 * 获取所有智能体
 */
export function getAgents(): Agent[] {
  try {
    const data = localStorage.getItem(STORAGE_KEY);
    if (data) {
      return JSON.parse(data);
    }
  } catch (error) {
    console.error('Failed to load agents:', error);
  }
  
  // 返回默认智能体
  return getDefaultAgents();
}

/**
 * 获取默认智能体列表
 */
function getDefaultAgents(): Agent[] {
  return [
    {
      id: 'dify-agent-1',
      name: '无限制对话',
      url: 'http://www.yourwebsite.net/chat/8OsikjjkF0yiLX5L',
      description: 'Dify 智能体 - 无限制对话',
      icon: 'MessageSquare',
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString(),
    },
  ];
}

/**
 * 保存智能体列表
 */
function saveAgents(agents: Agent[]): void {
  try {
    localStorage.setItem(STORAGE_KEY, JSON.stringify(agents));
  } catch (error) {
    console.error('Failed to save agents:', error);
    throw new Error('保存失败，请检查存储空间');
  }
}

/**
 * 添加新智能体
 */
export function addAgent(agent: Omit<Agent, 'id' | 'createdAt' | 'updatedAt'>): Agent {
  const agents = getAgents();
  
  const newAgent: Agent = {
    ...agent,
    id: `agent-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
    createdAt: new Date().toISOString(),
    updatedAt: new Date().toISOString(),
  };
  
  agents.push(newAgent);
  saveAgents(agents);
  
  return newAgent;
}

/**
 * 更新智能体
 */
export function updateAgent(id: string, updates: Partial<Omit<Agent, 'id' | 'createdAt'>>): Agent {
  const agents = getAgents();
  const index = agents.findIndex(a => a.id === id);
  
  if (index === -1) {
    throw new Error('智能体不存在');
  }
  
  agents[index] = {
    ...agents[index],
    ...updates,
    updatedAt: new Date().toISOString(),
  };
  
  saveAgents(agents);
  return agents[index];
}

/**
 * 删除智能体
 */
export function deleteAgent(id: string): void {
  const agents = getAgents();
  const filtered = agents.filter(a => a.id !== id);
  
  if (filtered.length === agents.length) {
    throw new Error('智能体不存在');
  }
  
  saveAgents(filtered);
}

/**
 * 根据 ID 获取智能体
 */
export function getAgentById(id: string): Agent | undefined {
  const agents = getAgents();
  return agents.find(a => a.id === id);
}

/**
 * 重置为默认智能体
 */
export function resetToDefault(): void {
  const defaultAgents = getDefaultAgents();
  saveAgents(defaultAgents);
}

/**
 * 导出智能体数据（用于备份）
 */
export function exportAgents(): string {
  const agents = getAgents();
  return JSON.stringify(agents, null, 2);
}

/**
 * 导入智能体数据（用于恢复）
 */
export function importAgents(jsonData: string): void {
  try {
    const agents = JSON.parse(jsonData);
    
    if (!Array.isArray(agents)) {
      throw new Error('数据格式错误');
    }
    
    // 验证数据结构
    for (const agent of agents) {
      if (!agent.id || !agent.name || !agent.url) {
        throw new Error('数据格式错误：缺少必要字段');
      }
    }
    
    saveAgents(agents);
  } catch (error) {
    if (error instanceof Error) {
      throw new Error(`导入失败: ${error.message}`);
    }
    throw new Error('导入失败');
  }
}

